#include "paintboardwidget.h"
#include "ui_paintboardwidget.h"

#include <QGraphicsRectItem>
#include <QGraphicsScene>
#include <QSpinBox>
#include <QGraphicsProxyWidget>
#include <QStyleOptionGraphicsItem>
#include <QDebug>

CPaintBoardWidget::CPaintBoardWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::CPaintBoardWidget)
    , m_scene(new QGraphicsScene)
{
    ui->setupUi(this);

    Init();
}

CPaintBoardWidget::~CPaintBoardWidget()
{
    delete ui;
}

void CPaintBoardWidget::Init()
{
    ui->graphicsView->setScene(m_scene);

    m_scene->setSceneRect(0,0, 200, 200);

    m_scene->addItem(new QGraphicsRectItem(QRect(0,0,200,200)));
    m_scene->addItem(new QGraphicsRectItem(QRect(0,0,50,50)));
    m_scene->addItem(new QGraphicsRectItem(QRect(50,50,50,50)));

    auto pItem = new QGraphicsRectItem(QRect(0,10,50,50));
    pItem->setPen(QPen(Qt::red));
    pItem->setPos(50,50);
    m_scene->addItem(pItem);


    auto pSubItem = new QGraphicsRectItem(QRect(0,20,50,50), pItem);
    pSubItem->setPen(QPen(Qt::green));
    //pSubItem->setPos(50,50);
    auto pt = pSubItem->pos();
    //m_scene->addItem(pSubItem);

    auto pScaleItem = new CScaleItem(QRect(10,10,50,50));
    pScaleItem->setPos(10,140);
    m_scene->addItem(pScaleItem);
}

CScaleItem::CScaleItem(const QRect &rect, QGraphicsItem *parent)
    : QGraphicsItem(parent)
    , m_rect(rect)
{
    QRectF subRect(rect.left()+10, rect.top()+10, rect.width()-20,rect.height()-20);
    m_subItem = new QGraphicsRectItem(subRect, this);
    setAcceptedMouseButtons(Qt::LeftButton);
}

CScaleItem::~CScaleItem()
{

}

QRectF CScaleItem::boundingRect() const
{
    return m_rect;
}

void CScaleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->save();
    painter->setPen(Qt::blue);
    painter->drawRect(m_rect);
    painter->restore();
}

void CScaleItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    qDebug() << "this";
    qDebug() << "sceneBoundingRect " << sceneBoundingRect();
    qDebug() << "boundingRect " << boundingRect();

    qDebug() << "subItem";
    qDebug() << "sceneBoundingRect " << m_subItem->sceneBoundingRect();
    qDebug() << "boundingRect " << m_subItem->boundingRect();

    qDebug() << "map";
    QRectF parentRtf = mapRectToScene(boundingRect());
    qDebug() << "mapRectToScene(boundingRect()) " << parentRtf;
    QRectF rtf = parentRtf;
    rtf = m_subItem->mapRectFromScene(rtf);
    qDebug() << "mapRectFromScene(rtf)" << rtf;
}

void CScaleItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{

}

void CScaleItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{

}
